package com.lzq.his.controller;

import com.lzq.his.domain.CalculationInput;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/calculate")
public class CalculationController {

    @PostMapping("/factorial-and-sum")
    public String factorialAndSum(@Valid @RequestBody CalculationInput input) {
        long factorial = factorial(input.getN());
        long sum = sumUpTo(input.getN());
        return "阶乘：" + factorial + " 和：" + sum;
    }

    @PostMapping("/factorials")
    public String factorialsUpTo(@RequestBody CalculationInput input) {
        List<Long> factorials = new ArrayList<>();
        for (int i = 1; i <= input.getN(); i++) {
            factorials.add(factorial(i));
        }
        System.out.println(factorials);
        // 求factorials的和
        long sum = factorials.stream()
                .mapToLong(Long::longValue)
                .sum();

        return String.valueOf(sum);
    }

    @PostMapping("/primes")
    public ResponseEntity<List<Integer>> primesUpTo(@RequestBody CalculationInput input) {
        List<Integer> primes = findPrimes(input.getN());
        return ResponseEntity.ok(primes);
    }

    @PostMapping("/quadratic-equation")
    public ResponseEntity<List<Double>> quadraticEquationRoots(@RequestParam double a, @RequestParam double b, @RequestParam double c) {
        List<Double> roots = solveQuadraticEquation(a, b, c);
        return ResponseEntity.ok(roots);
    }

























    private long factorial(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }
//
    private long sumUpTo(int n) {
        long sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }

    private List<Integer> findPrimes(int n) {
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                primes.add(i);
            }
        }
        return primes;
    }

    private boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    private List<Double> solveQuadraticEquation(double a, double b, double c) {
        List<Double> roots = new ArrayList<>();
        double discriminant = b * b - 4 * a * c;
        if (discriminant >= 0) {
            double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
            roots.add(root1);
            roots.add(root2);
        }
        return roots;
    }
}